<?php

/**
 * @author      :   QuangLT
 * @name        :   BlockController
 * @copyright   :   Fpt Online
 * @todo        :   News Controller
 */
class Euro2012_BlockController extends Zend_Controller_Action {

    /**
     * init of controller
     */
    public function init() {
        //Disable layout
    }

    /**
     * Default action 
     */
    public function indexAction() {
        //nothing
    }

    /**
     * Final template trang bong da quoc te
     * @author : phongtx@fpt.net
     */

    /**
     * block hot news action 
     */
    public function gethotnewsAction() {
        $cate_id = $this->_request->getParam('CategoryID');
        $limit = $this->_request->getParam('Limit');
        $template = $this->_request->getParam('view');
        //Get instance
        $instanceDB = News::getInstance();
        //default articleType
        $articleType = NULL;//ARTICLE;

        if (empty($cate_id)) {
            $cate_id = SITE_ID;
            //homepage: get all type
            $articleType = NULL;
        }
        

        //Result hot news
        if($cate_id == SITE_ID)
        {
            /* Get box hot news */
            $arrParams = array(
                'category_id' => $cate_id,
                'article_type' => $articleType,
                'limit' => $limit,
                'offset' => 0,
                'site_id' => SITE_ID
            );
 
            $arrArticleID = $instanceDB->getListArticleByHot($arrParams);
        }
        else
        {
            $arrArticleID = $instanceDB->getListTopArticle($cate_id, $limit, 0, $articleType);
        }
       
        
        $arrHotNewsResult = $instanceDB->getDetailArticleByIDs($arrArticleID['data']);

        //Assign to view
        $this->view->arrHotNewsResult = $arrHotNewsResult;

        //Check template
        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/gethotnews/' . $template);
        }
    }

    /**
     * block hot news action
     * @edit: TriNT
     */
    public function gettopnewsAction() {
        $catID = $this->_request->getParam('categoryID');
        $template = $this->_request->getParam('view', '');
        $limit = $this->_request->getParam('Limit', '');
        //var_dump($this->_request->getParams());die;
        //Get instance
        $instanceDB = News::getInstance();

        $arrBoxHotNews = array();

        /* Get box hot news */
        $arrBoxHotNews['topnews'] = array();
        //get list articleid 
      
        $arrArticle = $instanceDB->getListArticleEachCateByTime($limit);
        //get detail Article by list id
        if (!empty($arrArticle)) {
            $arrArticle["data"] = $instanceDB->getDetailArticleByIDs($arrArticle);
            $arrBoxHotNews['topnews'] = $arrArticle["data"];
        }

         
        $instanceStatictis = Statictis::getInstance();
        $arrComment = $instanceStatictis->getTopCommentArticle(SITE_ID, $limit);

        //get detail Article by list id
        if (!empty($arrComment)) {
            $arrComment = $instanceDB->getDetailArticleByIDs($arrComment);
            $arrBoxHotNews['topcomment'] = $arrComment;
        }
        //get top view
        $arrView = $instanceStatictis->getTopViewArticle(NULL, SITE_ID, $limit);

        //get detail Article by list id
        if (!empty($arrView)) {
            $arrView = $instanceDB->getDetailArticleByIDs($arrView);
            $arrBoxHotNews['topview'] = $arrView;
        }

        //Assign to view
        $this->view->arrTopNews = $arrBoxHotNews;

        //Check template
        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/gettopnews/' . $template);
        }
    }

    /**
     * get article by category
     * Block QuangLT
     * @edit: TriNT
     */
    public function getarticlebycategoryAction() {
        $catID = $this->_request->getParam('CategoryID', NULL);
        $limit = $this->_request->getParam('Limit', '');
        $template = $this->_request->getParam('view', '');
        // Get news instance
        $newsModel = News::getInstance();
        //get list articleid
        $arrArticle = $newsModel->getListTopArticle($catID, $limit, 0, NULL);
        //get detail Article by list id
        if (!empty($arrArticle) && $arrArticle["total"] > 0) {
            $arrArticle["data"] = $newsModel->getDetailArticleByIDs($arrArticle["data"]);
        }
        //Assign
        $this->view->arrData = $arrArticle["data"];
        $this->view->articleCategoryID = trim($catID);
        //Check view and render
        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/getarticlebycategory/' . $template);
        }
    }

    /**
     * block get video noi bat index page
     * @author TriNT
     */
    public function gethotvideophotoAction() {
        $limitVideo = $this->_request->getParam('LimitVideo', LIMIT_NEW_VIDEO);
        $limitPhoto = $this->_request->getParam('LimitPhoto', LIMIT_NEW_PHOTO);
        $template = $this->_request->getParam('view', 'common/box_hotvideo.phtml');
        //============================== Get hot video =======================================
        $newsModel = News::getInstance();
        //get list articleid
        $arrVideoID = $newsModel->getListTopArticle(CATE_ID_VIDEO, $limitVideo, 0, VIDEO );
        
        //get detail Article by list id
        if (!empty($arrVideoID) && !empty ($arrVideoID["data"])) {
            $arrVideoID["data"] = $newsModel->getDetailArticleByIDs($arrVideoID["data"]);
        }
        
        $arrNewVideo = array();
        //split array for 4 array
        if (!empty($arrVideoID["data"])) {
            for ($i = 0; $i < 4; $i++) {
                $arrObj = array_splice($arrVideoID["data"], 0, 4);
                if (!empty($arrObj))
                    $arrNewVideo[$i] = $arrObj;
            }
        }
        //============================== Get hot photo =======================================
        //get list articleid
        $arrPhotoID = $newsModel->getListTopArticle( CATE_ID_PHOTO, LIMIT_NEW_PHOTO, 0, ALBUM);
        //get detail Article by list id
        if (!empty($arrPhotoID) && !empty ($arrPhotoID["data"]) ) {
            $arrPhotoID["data"] = $newsModel->getDetailArticleByIDs($arrPhotoID["data"]);
        }
        $arrNewPhoto = array();
        //split array for 4 array
        if (!empty($arrPhotoID["data"])) {
            for ($i = 0; $i < 2; $i++) {
                $arrObjPhoto = array_splice($arrPhotoID["data"], 0, 4);
                if (!empty($arrObjPhoto))
                    $arrNewPhoto[$i] = $arrObjPhoto;
            }
        }
        $this->view->arrHotVideo = $arrNewVideo;
        $this->view->arrHotPhoto = $arrNewPhoto;

        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/gethotvideophoto/' . $template);
        }
    }

    /**
     * Get host match
     * Using at home page 
     * @author nhanva@fpt.net
     */
    public function gethotmatchAction() {

        // Get view
        $strPosition = $this->_request->getParam('position', NULL);
        $cate_id = $this->_request->getParam('cateid', SITE_ID);
        $template = $this->_request->getParam('view', '');

        // Get category
        $arrParamParent = Fpt_Global::getParentParams();
        if (isset($arrParamParent['cateid'])) {
            $cate_id = $arrParamParent['cateid'];
        }

        // Init instance match
        $instanceHotMatch = Match::getInstance();

        // Get hot match for home
        $arrHotMatch = $instanceHotMatch->getHotMatch($strPosition, $cate_id);
        
        $this->view->arrHotMatch = $arrHotMatch;

        //Check template
        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/getHotMatch/' . $template);
        }
    }

    public function advertiseAction() {
        //Get template
        $template = $this->_request->getParam('view', '');

        //Check template
        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/advertise/' . $template);
        }
    }

    /**
     * More Photo Action
     * @author TriNT
     */
    public function showmoreAction() {
        $this->_helper->layout->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isXmlHttpRequest()) {
            //init model category
            $newsModel = News::getInstance();
            $limit = LIMIT_SHOWMORE_PHOTO_SITE; // $this->getRequest()->getParam('limit', LIMIT_SHOWMORE_PHOTO_SITE);
            $cateid = $this->getRequest()->getParam('cateid', CATE_ID_PHOTO);
            $page = $this->getRequest()->getParam('page', 1);
            //excluses article
            $excluse = $this->getRequest()->getParam('excluse', NULL);
            $intStart = ($page - 1) * LIMIT_NEW_PHOTO_SITE;

            //get list articleid
            $arrNewPhotoResult = $newsModel->getListTopArticle($cateid, $limit, $intStart, ALBUM, $excluse);
			
            //get detail Article by list id
            if (!empty($arrNewPhotoResult) && !empty ($arrNewPhotoResult["data"])) {
                $arrNewPhotoResult["data"] = $newsModel->getDetailArticleByIDs($arrNewPhotoResult["data"]);
            }
            $arrNewPhotoResult['total'] = count($arrNewPhotoResult["data"]) >= LIMIT_SHOWMORE_PHOTO_SITE ? $intStart+LIMIT_SHOWMORE_PHOTO_SITE + 1 : 0;         
          
		   $this->view->assign('arrNewPhotoResult', $arrNewPhotoResult['data']);
            $tpl['html'] = $this->view->render('photo/box/ajax_photo.phtml');
            echo Zend_Json::encode(array('error' => 0, 'html' => trim($tpl['html']), 'next' => 2, 'total' => $arrNewPhotoResult['total']));
            exit(1);
        }//end if

        echo Zend_Json::encode(array('error' => 0, 'html' => ''));
        exit(1);
    }

    /**
     * get list photo by albumId
     * AJAX
     */
    public function getlistphotoAction() {
        //Disable layout
        $this->_helper->layout->disableLayout(true);

        //Get params
        $articleId = (int)$this->_request->getParam('albumId', 0);
        $albumName = $this->_request->getParam('albumName');
        $limit = $this->_request->getParam('limit', LIMIT_PHOTO);
        $offset = $this->_request->getParam('offset', 0);

        if($articleId > 0 && $articleId < 5000000){
            //init model news
            $newsModel = News::getInstance();

            //Get list photo
            $arrPhotos = $newsModel->getObjectReferenceByArticleID($articleId, $limit, $offset);
            //Assign to view
        }else{
            $arrPhotos = array();
        }
        $this->view->arrPhotos = $arrPhotos;
        $this->view->albumName = $albumName;
    }

     public function gettopnewsoncategoryAction() {
        $catID = $this->_request->getParam('CategoryID','');
        $type = $this->_request->getParam('ArticleType', VIDEO);
        $limit = $this->_request->getParam('Limit', LIMIT_FOOTBALL_VIDEO);
        $offset = 0;
        $template = $this->_request->getParam('view', '');
        //Get model instance
        $instanceDB = News::getInstance();

        /* Get box football video */
        $arrListID = $instanceDB->getListTopArticle($catID, $limit, $offset, VIDEO);
        $arrData = array();
        if(!empty ($arrListID['data']))
        {
            $arrData = $instanceDB->getDetailArticleByIDs($arrListID['data']);
        }
        //$arrResult = array();
        if(!empty ($arrData))
        {
            $arrResult['article'] = array_values($arrData);
            for($i=0; $i<count($arrResult['article']); $i++) {
                $intArticleID = (int)$arrResult['article'][$i]['article_id'];
                if($intArticleID == 0){
                    continue;
                }
                $arrResult['video'] = array_values($instanceDB->getObjectReferenceByArticleID($intArticleID, $limit));
            }
            //Assign to view
            $this->view->arrResult = $arrResult;
        }
        
        $this->view->cateID = $catID;
        //Check template

        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/gettopnews/' . $template);
        }
    }

    /**
     * @todo: display table ranking
     * @author : QuangTM
     */
    public function tablerankingAction() {
        // Get models' instance
        $teamSeasonModel = TeamSeason::getInstance();
        $leagueModel = League::getInstance();
        $seasonModel = Season::getInstance();

        // Get list league
        $arrLeague = $leagueModel->getListLeagueByIDs(array(1, 2, 3, 4));

        // Get list season
        $arrSeason = $seasonModel->getListSeasonByIDs(array(1, 2, 3, 4));

        $english = array(
            'tableRanking' => $teamSeasonModel->getListTableRanking(1, 1),
            'seasonID' => 1,
            'leagueID' => 1,
            'leagueName' => $arrLeague[0]['Name'],
            'seasonName' => $arrSeason[0]['NameSeason'],
        );
        $italy = array(
            'tableRanking' => $teamSeasonModel->getListTableRanking(3, 3),
            'seasonID' => 3,
            'leagueID' => 3,
            'leagueName' => $arrLeague[2]['Name'],
            'seasonName' => $arrSeason[2]['NameSeason'],
        );
        $spanish = array(
            'tableRanking' => $teamSeasonModel->getListTableRanking(2, 2),
            'seasonID' => 2,
            'leagueID' => 2,
            'leagueName' => $arrLeague[1]['Name'],
            'seasonName' => $arrSeason[1]['NameSeason'],
        );
        $german = array(
            'tableRanking' => $teamSeasonModel->getListTableRanking(4, 4),
            'seasonID' => 4,
            'leagueID' => 4,
            'leagueName' => $arrLeague[3]['Name'],
            'seasonName' => $arrSeason[3]['NameSeason'],
        );

        $this->view->assign(array(
            'english' => $english,
            'italy' => $italy,
            'german' => $german,
            'spanish' => $spanish
        ));
    }

    /**
     * Get hot news of Teams 
     * Block QuangLT
     */
    public function gethotnewsofteamAction() {
        //Get params
        $teamID = $this->_request->getParam('TeamID', 1);
        $limit = $this->_request->getParam('Limit', 6);
        $template = $this->_request->getParam('view', '');
        //Get parent params
        $arrParentParams = Fpt_Global::getParentParams();

        //Get model instance
        $instanceDB = News::getInstance();
        $teamModel = TeamSeason::getInstance();
        //Get team info
        $teamInfo = $teamModel->getDetailTeam($teamID);
        //Get array data Article of team
        $arrResult = $instanceDB->getListArticleByTag($teamID, $limit, 0, ARTICLE);
        if (!empty($arrResult) && !empty ($arrResult["data"])) {
            $arrResult["data"] = $instanceDB->getDetailArticleByIDs($arrResult["data"]);
        }

        //$arrResult = $instanceDB->getHotNewsOfTeam($teamID, $limit);
        //Assign to view
        $this->view->arrResult = $arrResult["data"];
        $this->view->arrTeamInfo = $teamInfo;
        $this->view->arrParentParams = $arrParentParams;

        //Check template
        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/gethotnewsofteam/' . $template);
        }
    }

    /**
     * Lich thi dau block
     * @author QuangTM
     */
    public function fixtureAction() {
        // Determine unix time today (ignore hour, minute, second)
        $unixTimeToday = intval(strtotime(date('Y/m/d')));
        // Determine day of week
        $dayOfWeek = date('N');
        // Determine unix time of monday
        $unixTimeModay = $unixTimeToday - ($dayOfWeek - 1) * 86400;
        // Determine unix time of sunday
        $unixTimeSunday = $unixTimeToday + ( 7 - $dayOfWeek + 1) * 86400 - 1;

        // Get model match
        $model = Match::getInstance();

        // Get fixture of Barclays Premier League
        $premierLeagueFixture = $model->getMatchInWeek(1, 1, $unixTimeModay, $unixTimeSunday);

        // Get fixture of la liga
        $laLigaFixture = $model->getMatchInWeek(2, 2, $unixTimeModay, $unixTimeSunday);

        // Get fixture serie A
        $serieAFixture = $model->getMatchInWeek(3, 3, $unixTimeModay, $unixTimeSunday);

        //Get fixture of BUNDESLIGA
        $bundesligaFixture = $model->getMatchInWeek(4, 4, $unixTimeModay, $unixTimeSunday);

        $this->view->assign('premierLeagueFixture', $premierLeagueFixture);
        $this->view->assign('laLigaFixture', $laLigaFixture);
        $this->view->assign('serieAFixture', $serieAFixture);
        $this->view->assign('bundesligaFixture', $bundesligaFixture);
    }

    /**
     * Get top players table 
     */
    public function topplayerAction() {
        $seasonId = intval($this->_request->getParam('SeasonID', 0));
        $template = $this->_request->getParam('view', '');
        if ($seasonId) {
            // Get model player champion instance
            $playerChampionPlayer = PlayerChampion::getInstance();

            // Get list players
            $arrTopPlayers = $playerChampionPlayer->getListTopPlayers($seasonId);
            
            // Assign to view
            $this->view->assign('arrTopPlayers', $arrTopPlayers);
        }
        
        //Check template
        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/topplayer/' . $template);
        }
    }

    /**
     * load ajax list video hot + new
     * @author TriNT
     */
    public function loadvideoAction() {
        $this->_helper->layout->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isXmlHttpRequest()) {
            $newsModel = News::getInstance();
            /* ========= START GET LIST VIDEO NEW ========= */
            //init page
            $intPage = $this->_request->getParam('page', 1);
            $cateid = $this->getRequest()->getParam('cateid', CATE_ID_VIDEO);
            //excluses article
            $excluse = $this->getRequest()->getParam('excluse', NULL);
            if ($excluse !== NULL)
                $excluse = Zend_Json::decode($excluse);
            //echo $excluse; die;
            //Set start offset
            $perpage = LIMIT_NEW_VIDEO_SITE;
            $intStart = ($intPage - 1) * $perpage;

            $newsModel = News::getInstance();
            $arrNewVideoResult = array(); //result
            //get list article id
            // $arrNewVideoResult = $newsModel->getListTopArticle($cateid, $perpage, $intStart, VIDEO, $excluse);
            $arrNewVideoResult = $newsModel->getListTopArticle( $cateid, $perpage, $intStart);
            // get detail article by list id
            if (!empty($arrNewVideoResult) ) {
                $arrNewVideoResult["data"] = $newsModel->getDetailArticleByIDs($arrNewVideoResult["data"]);
            }

            //init Paging
            $intTotal = count($arrNewVideoResult["data"]);
            $intTotalPage = ceil($intTotal / $perpage);

            $strUri = 'loadvideolist';
            // assign to view
            $this->view->arrNewVideoResult = $arrNewVideoResult["data"];
            //paging
            $this->view->total = $intTotal;
            $this->view->Pagination = $this->view->PaginationAjax($intTotal, $intPage, $strUri, $cateid, $perpage);

            $tpl['html'] = $this->view->render('video/box/ajaxlistvideo.phtml');
            /* ========= END GET LIST VIDEO NEW ========= */
            echo Zend_Json::encode(array('error' => 0, 'html' => trim($tpl['html']), 'next' => 2));
            exit(1);
        }//end if

        echo Zend_Json::encode(array('error' => 0, 'html' => ''));
        exit(1);
    }

    /**
     * get block facebook fan page
     * @author QuangLT 
     */
    public function facebookfanpageAction() {
        //render html
    }
    /**
     * Get top view video list
     * @author TriNT
     */
     public function topviewvideoAction(){
         //get cateID
        $template = $this->_request->getParam('view', '');
        $articleType = $this->_request->getParam('ArticleType', VIDEO);
        $cateid = $this->_request->getParam('CategoryID', CATE_ID_VIDEO);
        $limit = $this->_request->getParam('Limit', LIMIT_TOPVIEW_VIDEO);

        //Get instance
        $instanceStatictis = Statictis::getInstance();
         //get top view
        $arrView = $instanceStatictis->getTopViewArticle($articleType, $cateid, $limit);
        //echo "<pre>"; print_r($arrView); //die;
        //get detail Article by list id
        $arrTopViewVideo = array();
        if (!empty($arrView)) {
            //Get instance
            $instanceDB = News::getInstance();
            $arrTopViewVideo = $instanceDB->getDetailArticleByIDs($arrView);
        }
        // assign to view
        $this->view->arrTopViewVideo = $arrTopViewVideo;
        //Check template
        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/topviewvideo/' . $template);
        }
     }
     /**
     * block hot news action 
     */
    public function othernewsAction() {
        //Get instance
        $instanceDB = News::getInstance();
        
        $parentParams = Fpt_Global::getParentParams();
        $intArticleId = $parentParams['id'];
        $arrArticleDetail = $instanceDB->getDetailArticleByIDs(array($intArticleId));
        $arrArticleDetail = $arrArticleDetail[$intArticleId];

   
        //Get list other news
        $arrPamram = array(
            'category_id' => $arrArticleDetail['category_id'],
            'todate'    => $arrArticleDetail['creation_time'],
            'fromdate'  => 0,
            'limit'     => LIMIT_OTHER_NEWS,
            'offset'    => 0,
            'intArticleId' => array($intArticleId)
        );

        //Result other news
        $arrArticleIds = $instanceDB->getListOtherArticleByCateCreateTime($arrPamram);
        $arrDetailArticle = array();
        if(!empty ($arrArticleIds['data']))
        {
            // Get article detail
            $arrDetailArticle = $instanceDB->getDetailArticleByIDs($arrArticleIds['data']);
        }
        $this->view->arrOtherArticleDetail = array_values($arrDetailArticle);

        //Check template
        if (!empty($template)) {
            $this->_helper->viewRenderer->setNoRender();
            echo $this->view->render('block/' . $template);
        }
    }
}